class GoLibrespot < Formula
  desc "Spotify client"
  homepage "https://github.com/devgianlu/go-librespot"
  url "https://github.com/devgianlu/go-librespot/archive/refs/tags/v0.5.3.tar.gz"
  sha256 "d4ca2f61e74a81462ec78f3d72c7814c9545c4594c3a1081904966fa9f0a2487"
  license "GPL-3.0-only"
  head "https://github.com/devgianlu/go-librespot.git", branch: "master"

  bottle do
    sha256 cellar: :any,                 arm64_tahoe:   "b1c36daf56b4568ac60f49179e849d19af6133bc6f614c47b00c321d52c23fa3"
    sha256 cellar: :any,                 arm64_sequoia: "706f7232e2a179394b70947954ee7d7e8b3e3c3cae347e1cbaa4003729cab93e"
    sha256 cellar: :any,                 arm64_sonoma:  "24800e1241744e3550220c3021b4ca25f2a9a812f412c0ce95e332ab6a13e4e0"
    sha256 cellar: :any,                 sonoma:        "b90c39075777aab2208f9220c2ffe17c0c3292517205bef03b161f2733e6e144"
    sha256 cellar: :any_skip_relocation, arm64_linux:   "479d7d2bff706615a91aed328b8c89cc09ad9707f09c9a354b71964b480bb4b8"
    sha256 cellar: :any_skip_relocation, x86_64_linux:  "70a57c7754117a6af50a3f566fc78673407a462ae288280ccdd8ce9ee8b23a56"
  end

  depends_on "go" => :build
  depends_on "pkgconf" => :build
  depends_on "flac"
  depends_on "libogg"
  depends_on "libvorbis"

  on_linux do
    depends_on "alsa-lib"
  end

  def install
    ENV["CGO_ENABLED"] = "1" if OS.linux? && Hardware::CPU.arm?

    ldflags = %W[
      -s -w
      -X github.com/devgianlu/go-librespot.version=#{version}
    ]
    ldflags << "-X github.com/devgianlu/go-librespot.commit=#{Utils.git_short_head(length: 8)}" if build.head?

    system "go", "build", *std_go_args(output: bin/"go-librespot", ldflags: ldflags), "./cmd/daemon"

    # On macOS, create a minimal config that selects the correct backend.
    return unless OS.mac?

    (buildpath/"config.yml").write <<~YAML
      # Auto-generated by Homebrew. You can edit this file.
      # Use CoreAudio via AudioToolbox on macOS.
      audio_backend: audio-toolbox
    YAML
    pkgetc.install "config.yml"
  end

  def post_install
    (var/"log").mkpath
  end

  service do
    run [opt_bin/"go-librespot", "--config_dir", etc/"go-librespot"]
    keep_alive true
    log_path var/"log/go-librespot.log"
    error_log_path var/"log/go-librespot.log"
  end

  test do
    cfg = testpath/"config.yml"
    cfg.write <<~YAML
      volume_steps: not_a_number
    YAML

    output = shell_output("#{bin}/go-librespot --config_dir #{testpath} 2>&1", 1)
    assert_match "failed loading config", output
    assert_match "failed to unmarshal configuration", output
  end
end
